package cn.tedu.controller;

import cn.tedu.entity.RolesEntity;
import cn.tedu.service.RoleMenusService;
import cn.tedu.service.RoleService;
import cn.tedu.vo.JsonResult;
import cn.tedu.vo.PageEntity;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenusService roleMenusService;

    @Value("${pageHelper.pageSize}")
    private Integer pageSize;

    @RequestMapping("/doFindPageObjects")
    public JsonResult doFindObjects(String pageCurrent,String name){
        IPage<RolesEntity> iPage = roleService.selectPageExt(pageCurrent, pageSize,name);
        PageEntity<RolesEntity> pageEntity = new PageEntity<RolesEntity>();
        pageEntity.setRecords(iPage.getRecords())
                .setPageCurrent(pageCurrent)
                .setPageCount(iPage.getPages()+"")
                .setRowCount(iPage.getSize()+"");
        return new JsonResult(pageEntity);
    }

    @RequestMapping("/doSaveObject")
    public JsonResult doSaveObject(RolesEntity rolesEntity,Integer ... menuIds){


        rolesEntity.setCreatedUser("admin");
        rolesEntity.setModifiedUser("admin");
        rolesEntity.setCreatedTime(new Date());
        rolesEntity.setModifiedTime(new Date());
        roleService.save(rolesEntity);
        System.out.println(rolesEntity.getId());
        roleMenusService.saveRoleMenus(rolesEntity.getId(),menuIds);
        return  new JsonResult("保存成功");
    }
    @RequestMapping("/doUpdateObject")
    public JsonResult doUpdateObject(RolesEntity rolesEntity,String ... menuIds){
        System.out.println(rolesEntity);
        rolesEntity.setModifiedUser("admin");
        rolesEntity.setModifiedTime(new Date());
        UpdateWrapper<RolesEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",rolesEntity.getId());
        roleService.update(rolesEntity, updateWrapper);
        return  new JsonResult("保存成功");
    }
    @RequestMapping("/doDeleteObject")
    public JsonResult doDeleteObject(Integer id){
        roleService.removeById(id);
        return new JsonResult("删除成功");
    }

    @RequestMapping("/doFindObjectById")
    public JsonResult doFindObjectById(String id){
        RolesEntity byId = roleService.getById(id);
        return new JsonResult(byId);
    }
}
